
from . import base_parser


class MyHTMLParser(base_parser.BaseHTMLParser):
    TITLE = '江苏政府采购'
    HOST =  'http://www.ccgp-jiangsu.gov.cn/ggxx/gkzbgg/'

    headers= {}


    def __init__(self, host=None):
        
        if not host:
            host = self.HOST
        
        super(MyHTMLParser, self).__init__(host=host, headers=self.headers, cell_type='li' )
        self.host = host
        self.title = self.TITLE

        self.result_meta = {
            'len': 1,
            'href': ( 0, 'a', 'href' ),
            'title': ( 0, 'a', 'text' ),
            'date':  ( 0, 'a', ('text',1) ),
        }
        
    def handle_result_href(self, href):
        return 'www.ccgp-jiangsu.gov.cn/ggxx/gkzbgg/' + href

"""

    def handle_starttag(self, tag, attrs):
        #print("Encountered a start tag:", tag)
        #print("Encountered a start tag:", tag, self.tr, self.td )
        if tag.lower() == "li":   
            self.tr += 1
            self.links[self.tr] = {}


        elif tag.lower() == "a":   
            if len(attrs):
                for (variable, value) in attrs:   
                    if variable.lower() == "href":   
                        self.links[self.tr]['href'] = value
                        #print(value)

        self.tag = tag.lower()
        
    def handle_data(self, data):
        #print("Encountered some data  :", self.tr, self.td, data  )
        pass
        
        def get_cell():
            tr = self.links.get(self.tr, None)
            
            if tr != None :
                return tr

            return None
        
        def set_cell(fld, data):
            cell = get_cell()
            if cell != None :
                val = cell.get(fld, None)
                if val == None:
                    cell[fld] = []
                    val = cell[fld]

                val += [data]
        
        if self.tag == 'li':
            set_cell('date', data)

        if self.tag == 'a':
            set_cell('title', data)

    
    def handle_result(self):
        results = []
        for tr, link in self.links.items():
            
            date = link.get('date')
            if not date:
                continue
                
            if len( date ) > 1:
                continue
            
            href = link['href']
            title0 = link['title']
            title = title0[0]
            date = title0[1]
            date = date.strip()
            
            results += [{
                'href': 'www.ccgp-jiangsu.gov.cn/ggxx/gkzbgg/' + href, 
                'title': title, 
                'date': date 
            }]

        def fn(index, res):
            res['id'] = index+1
            return res


        results = [ fn(index, res) for index, res in enumerate( results ) ]
        return results

"""